<template>
  <div class="page add-split-bill-party">
    <awesome-picker
      ref="pickerAffiliation"
      :textTitle="pickerAffiliation.textTitle"
      colorTitle="#38ADFF"
      colorConfirm="#38ADFF"
      :data="pickerAffiliation.data"
      :anchor="pickerAffiliation.anchor"
      @confirm="handlePickerAffiliation"
    ></awesome-picker>
    <awesome-picker
      ref="reserveBranch"
      :textTitle="reserveBranch.textTitle"
      :data="reserveBranch.data"
      :anchor="reserveBranch.anchor"
      @confirm="(v)=>handleConfirm('reserveBranch',v,reserveBranch.data)"
      ></awesome-picker>
    <awesome-picker
      ref="reserveBank"
      :textTitle="reserveBank.textTitle"
      :data="reserveBank.data"
      :anchor="reserveBank.anchor"
      @confirm="(v)=>handleConfirm('reserveBank',v,reserveBank.data)"
      ></awesome-picker>
    <awesome-picker
      ref="reserveBranchName"
      :textTitle="reserveBranchName.textTitle"
      :data="reserveBranchName.data"
      :anchor="reserveBranchName.anchor"
      @confirm="(v)=>handleConfirm('reserveBranchName',v,reserveBranchName.data)"
      ></awesome-picker>
    <div class="scroll-view">
      <customHeader middleTitle="填写分账方信息" @leftCallBack="handleBack"/>
      <div class="page-body">
        <div class="section-title">
          <span class="setting">
            设置<font>第{{ billedStoresCount + 1 }}个分账方</font>
          </span>
        </div>
        <ul class="mine-options">
          <li class="option-item">
              <span class="left">账户类型</span>
              <div class="right" @click="showPicker('pickerAffiliation')">
                <span v-if="formData.partyRole =='0'" class="placeholder">请选择</span>
                <span v-if="formData.partyRole !='0'" class="value">{{ this.pickerAffiliation.selected.value }}</span>
                <span class="right-icon">
                  <i class="zhk-list_rarrow"></i>
                </span>
              </div>
          </li>
        </ul>
        <ul class="mine-options">
          <li class="option-item">
              <span class="left">开户名称</span>
              <div class="right">
                <inputClear
                  type="text"
                  warpClass="add-split-bill-party-input"
                  v-model="formData.accountName"
                  placeholder="请填写户卡名称"
                  :maxlength="20"
                  :max="20"
                />
              </div>
          </li>
          <li class="option-item">
              <span class="left">银行账号</span>
              <div class="right">
                <inputClear
                  type="tel"
                  warpClass="add-split-bill-party-input"
                  v-model="formData.accountNo"
                  placeholder="请填写银行账号"
                  :maxlength="20"
                  :max="20"
                  onkeyup="this.value=this.value.replace(/\D/g,'')"
                  onafterpaste="this.value=this.value.replace(/\D/g,'')"
                />
              </div>
          </li>
          <li class="option-item" v-if="formData.partyRole == 1">
              <span class="left">开户人身份证号码</span>
              <div class="right">
                <inputClear
                  type="text"
                  warpClass="add-split-bill-party-input"
                  v-model="formData.legalIdCardNo"
                  placeholder="请填写开户人身份证号码"
                  :maxlength="20"
                  :max="20"
                />
              </div>
          </li>
        </ul>
        <ul class="mine-options">
          <li class="option-item">
              <span class="left">开户行所在地区</span>
              <div class="right" @click="showPicker('reserveBranch')">
                <span v-if="formData.reserveBranchAreaName ==''" class="placeholder">{{ reserveBranch.tip }}</span>
                <span v-if="formData.reserveBranchAreaName !=''" class="value">{{ formData.reserveBranchAreaName }}</span>
                <span class="right-icon">
                  <i class="zhk-list_rarrow"></i>
                </span>
              </div>
          </li>
          <li class="option-item">
              <span class="left">开户银行</span>
              <div class="right" @click="showPicker('reserveBank')">
                <span v-if="formData.reserveBankName == ''" class="placeholder">{{ reserveBank.tip }}</span>
                <span v-if="formData.reserveBankName != ''" class="value">{{ formData.reserveBankName }}</span>
                <span class="right-icon">
                  <i class="zhk-list_rarrow"></i>
                </span>
              </div>
          </li>
          <li class="option-item">
              <span class="left">支行名称</span>
              <div class="right" @click="showPicker('reserveBranchName')">
                <span v-if="formData.reserveBranchName == ''" class="placeholder">{{ reserveBranchName.tip }}</span>
                <span v-if="formData.reserveBranchName != ''" class="value">{{ formData.reserveBranchName }}</span>
                <span class="right-icon">
                  <i class="zhk-list_rarrow"></i>
                </span>
              </div>
          </li>
        </ul>
      </div>
      <div class="btn-wrap">
        <span
          class="btn"
            :class="{disabled:disabledSubmit}"
            @click="submit"
            >提交并设置分账比例
        </span>
      </div>
    </div>
  </div>
</template>

<script>
import Vue from "vue";
import customHeader from "../../../components/header/header";
import inputClear from "../../../components/inputClear/inputClear";
import AwesomePicker from "vue-awesome-picker";
Vue.use(AwesomePicker);
import { Toast, MessageBox } from "mint-ui";
export default {
  name: "addEmployee",
  data() {
    return {
      billedStoresCount: this.$route.query.billedStoresCount || 0,
      shopInfo: JSON.parse(this.$route.query.shopInfo),
      //表单数据
      formData:{
        partyRole: 0,
        accountName: '',
        accountNo: '',
        legalIdCardNo: '',
        reserveBankCertName:'',//公户开户名
        reserveBankCardNo:'',//公户卡号
        reserveBranchProvince:'',//公户开户行省code
        reserveBranchProvinceName:'',//公户开户行省名称
        reserveBranchCity:'',//公户开户行城市code
        reserveBranchCityName:'',//公户开户行城市名称
        reserveBankId:'',//公户开户银行ID
        reserveBankName:'',//公户开户银行名称
        reserveBranchName:'',//公户支行名称
        reseveNuccCode:'',//公户网联机构号
        reserveContactLine:'',//公户联行号
        reserveBranchAreaName:'',//公户开户行拼接字段
        bankId:'',//开户银行ID
        bankCode:'',//开户银行名称
        branchName:'',//支行名称
        branchAreaName:'',//开户行拼接字段
      },
      pickerAffiliation: {
        anchor: [],
        textTitle: "请选择账户类型",
        data: [{ value: "对私" }, { value: "对公" }],
        selected: { value: "对私" }
      },
      //公户开户银行
      reserveBank:{
        tip:"请选择开户银行",
        anchor: [0],
        textTitle: "开户银行",
        data: []
      },
      //公户开户行所在地区
      reserveBranch:{
        tip:"请选择开户行所在地",
        anchor: [0],
        textTitle: "所属地区",
        data: []
      },
      //开户行所在地区
      branch:{
        tip:"请选择",
        anchor: [0],
        textTitle: "开户行所在地区",
        data: []
      },
      //公户支行名称
      reserveBranchName:{
        tip:"请选择支行名称",
        anchor: [0],
        textTitle: "选择支行",
        data: []
      },
      //支行名称
      branchName:{
        tip:"请选择",
        anchor: [0],
        textTitle: "支行名称",
        data: []
      },
    };
  },
  methods: {
    //弹窗选择回掉赋值
    handleConfirm(key,v,data){
      if(key == 'reserveBranch'){
        this.formData.reserveBranchAreaName = v[0].value + (v[1]?' - ':'') + (v[1]?v[1].value:'');
        this.formData.reserveBranchProvinceName = v[0].value || '';
        this.formData.reserveBranchCityName = v[1].value || '';
        this.formData.reserveBranchProvince = this.getId(data,v[0].value,1) || '';//省code
        this.formData.reserveBranchCity = this.getId(data,v[1].value,2) || '';//市code
        this[key].anchor = [v[0].index,v[1].index];


        //初始话
        this.reserveBank.data = [];
        this.reserveBank.anchor = [];
        this.formData.reserveBankId ="";
        this.formData.reserveBankName ="";
        this.reserveBranchName.data = [];
        this.formData.reserveBranchName = '';//支行名称
        this.formData.reserveBranchCode = '';//支行code
        this.formData.reseveNuccCode = '';
        this.formData.reserveContactLine = '';
        this.getReserveBank();
        return
      }
      if(key == 'reserveBank'){
        this.formData.reserveBankName = v[0].value;
        this.formData.reserveBankId = this.getId(data,v[0].value,1) || '';//开户行ID
        this[key].anchor = [v[0].index];
        this.reserveBranchItemVisible = false;
        this.reserveBranchName.data = [];
        this.formData.reserveBranchName = '';//支行名称
        this.formData.reserveBranchCode = '';//支行code
        this.formData.reseveNuccCode = '';
        this.formData.reserveContactLine = '';
        this.getReserveBranchName();
        return
      }
      if(key == 'branchName'){
        this.formData.branchName = v[0].value;
        this.formData.contactLine = this.getId(data,v[0].value,1) || '';//支行ID
        this[key].anchor = [v[0].index];
        return
      }
      if(key == 'reserveBranchName'){
        this.formData.reserveBranchName = v[0].value;
        this.formData.reserveContactLine = this.getId(data,v[0].value,1) || '';//支行ID（联行号
        this.formData.reserveNuccCode = data[v[0].index].nuccCode || '';//网联机构号
        this[key].anchor = [v[0].index];
        return
      }
      this[key].anchor = [v[0].index];
      this.formData[key] = this.getId(data,v[v.length-1].value,v.length);
    },
    showPicker(ref) {
      this.$refs[ref].show();
    },
    handlePickerAffiliation(v) {
      this.pickerAffiliation.anchor = v;
      this.pickerAffiliation.selected.value = v[0].value;
      if(this.pickerAffiliation.selected.value=="请选择"){
        this.formData.partyRole = 0;
      }else if(this.pickerAffiliation.selected.value=="对私"){
        this.formData.partyRole = 1;
      }else if(this.pickerAffiliation.selected.value=="对公"){
        this.formData.partyRole = 2;
      }
    },
    handleBack() {
      this.$router.go(-1);
    },
    //开户行所在地区数据处理
    resetBranchAreaData(data){
      const newData = [];
        data.map((item,index)=>{
          if(item.cityType == 'province'){
            const obj = {
              key:item.fuyouCityId,
              value:item.fuyouCityName,
              children:[]
            }
            newData.push(obj)
          }

        })
        data.map((item,index)=>{
          if(item.cityType == 'city'){
            const obj = {
              key:item.fuyouCityId,
              value:item.fuyouCityName,
              pid:item.fuyouCityPid
            }
            for(let i =0;i<newData.length;i++){
              if(newData[i].key == obj.pid){
                newData[i].children.push(obj)
              }
            }
          }
        })
      return newData
    },
    //开户行所在地区
    getCityMapped(){
      this.ajax({
        type: "get",
        url: "/newapp/AppMerchant/getCityMapped.do"
      })
        .then((response)=> {
          if (response && response.success) {
            const branchData = response.resultObject;
            this.branch.data = this.resetBranchAreaData(branchData);
            this.reserveBranch.data = this.resetBranchAreaData(branchData);
          } else {
            Toast("加载开户行所在地区失败");
          }
        })
        .catch((err) =>{

        });
    },
    //公户开户银行
    getReserveBank(){
      this.ajax({
        type: "get",
        url: "/app/AppMerchant/queryMerchantBankCode.do?province=" + (this.formData.reserveBranchProvince || '') +'&city='+(this.formData.reserveBranchCity || '')
      })
        .then((response)=> {
          if (response && response.success) {
            const bankData = response.resultObject;
            //对开户银行数据处理
            this.reserveBank.data = this.resetBankData(bankData)
          } else {
            Toast("加载公户开户银行失败");
          }
        })
        .catch((err) =>{
        });
      },
      //获取公户支行名称
      getReserveBranchName(){
        this.ajax({
          type: "get",
          url: "/app/AppMerchant/queryMerchantBankName.do?province=" + (this.formData.reserveBranchProvince || '') +'&city='+(this.formData.reserveBranchCity || '')+'&parentId='+(this.formData.reserveBankId || '')
        })
          .then((response)=> {
            if (response && response.success) {
              const branchData = response.resultObject;
              //对开户银行数据处理
              this.reserveBranchName.data = this.resetBranchData(branchData)
              this.reserveBranchItemVisible = true;
            } else {
              Toast("加载支行名称失败");
            }
          })
          .catch((err) =>{
          });
      },
      //获取支行名称
      getBranchName(){
        this.ajax({
          type: "get",
          url: "/app/AppMerchant/queryMerchantBankName.do?province=" + (this.formData.branchProvince || '') +'&city='+(this.formData.branchCity || '')+'&parentId='+(this.formData.bankId || '')
        })
        .then((response)=> {
          if (response && response.success) {
            const branchData = response.resultObject;
            //对开户银行数据处理
            this.branchName.data = this.resetBranchData(branchData)
            this.branchItemVisible = true;
          } else {
            Toast("加载支行名称失败");
          }
        })
        .catch((err) =>{

        });
    },
    //开户银行数据处理
    resetBankData(data){
      const newData = [];
      data.map((item)=>{
        const obj ={
          key:item.bankId,
          value:item.bankMainName
        };
        newData.push(obj);
      })
      return newData
    },
    //支行名称数据处理
    resetBranchData(data){
      const newData = [];
      data.map((item)=>{
        const obj ={
          key:item.contactLine,
          value:item.bankName,
          nuccCode:item.nuccCode,
        };
        newData.push(obj);
      })
      return newData
    },
    //根据value获取key
    getId(data,val,lev){
      if(lev == 1){
        for(let i =0; i<data.length;i++){
          if(data[i].value == val){
            return data[i].key || data[i].id;
          }
        }
      }
      if(lev == 2){
        for(let i =0; i<data.length;i++){
          for(let j =0; j<data[i].children.length;j++){
            let lev2Data =  data[i].children[j]
            if(lev2Data.value == val){
              return lev2Data.key || lev2Data.id;
            }
          }
        }
      }
      if(lev == 3){
        for(let i =0; i<data.length;i++){
          for(let j =0; j<data[i].children.length;j++){
            let lev2Data =  data[i].children[j]
            for(let n =0; n<lev2Data.children.length;n++){
              let lev3Data =  lev2Data.children[n];
              if(lev3Data.value == val){
                return lev3Data.key || lev3Data.id;
              }
            }
          }
        }
      }
      return
    },
    submit() {
      if (this.formData.partyRole == 0) {
        Toast("请选择账户类型");
        return;
      }

      if (this.formData.reserveBranchAreaName == '') {
        Toast("请选择开户行所在地");
        return;
      }
      if (this.formData.reserveBankName == '') {
        Toast("请选择开户银行");
        return;
      }
      if (this.formData.reserveBranchName == '') {
        Toast("请选择支行名称");
        return;
      }

      var params = {};
      if (this.formData.partyRole == 1) {
        if (this.formData.accountName == '') {
          Toast("请填写户卡名称");
          return;
        }
        if (this.formData.accountNo == '') {
          Toast("请填写银行账号");
          return;
        }
        if (this.formData.legalIdCardNo == '') {
          Toast("请填写开户人身份证号码");
          return;
        }
        params.accountType = '1';
        params.legalIdCardNo = this.formData.legalIdCardNo;
      }
      else if (this.formData.partyRole == 2) {
        if (this.formData.accountName == '') {
          Toast("请填写户卡名称");
          return;
        }
        if (this.formData.accountNo == '') {
          Toast("请填写银行账号");
          return;
        }
        params.accountType = '0';
        params.linkBankNo = this.formData.reserveContactLine;
      }

      params.supplierId = this.shopInfo.supplierId;
      params.shopId = this.shopInfo.shopId;
      params.merchantId = this.shopInfo.merchantId;
      params.merchantName = this.shopInfo.merchantName;
      params.accountName = this.formData.accountName;
      params.accountNo = this.formData.accountNo.replace(/\s+/g, '');;
      params.bankName = this.formData.reserveBankName;
      params.nuccCode = this.formData.reserveNuccCode;
      params.bankRegin = this.formData.reserveBranchAreaName;

      this.ajax({
        type: "post",
        data: params,
        url: "/newapp/shopSplit/addShopSplitAccount.do",
        controlLoading: true
      })
        .then(res => {
          if (res.success) {
            Toast("增加分账方成功!");
            setTimeout(() => {
              this.$router.back();
            }, 1000);
          } else {
            Toast(res.msg);
          }
        })
        .catch(err => {});
    },
  },
  computed: {
    disabledSubmit() {
      if (this.formData.partyRole == 0) {
        return true;
      }
      if (this.formData.accountName == '' || this.formData.accountNo == '') {
        return true;
      }
      if (this.formData.partyRole == 1) {
        if (this.formData.legalIdCardNo == '') {
          return true;
        }
      } else if (this.formData.partyRole == 2) {
        if (this.reserveBranchAreaName == '' || this.formData.reserveBankName == '' || this.formData.reserveBranchName == '') {
          return true;
        }
      }
      return false;
    }
  },
  created() {
    console.log('shop:', this.shopInfo);
  },
  mounted(){
    this.getCityMapped();
  },
  components: {
    customHeader,
    inputClear
  }
};
</script>
<style lang='scss' scoped>
@import "addSplitBillParty";
</style>
<style lang="scss">
@import "../../../style/public";
.add-split-bill-party-input {
  text-align: right !important;
  @include remCalc(font-size, 32, !important);
}
.picker-title .pt-cancel {
    color: #95989A !important;
    font-size: 0.8rem !important;
    font-family: PingFangTC-Regular !important;
    font-weight: 400 !important;
}
.picker-title .pt-submit {
  font-size: 0.8rem !important;
  font-family: PingFangTC-Regular !important;
  font-weight: 400 !important;
  color: #FF3D34 !important;
}
.picker .picker-title > h4 {
    font-size: 0.9rem !important;
    font-family: PingFangSC-Medium !important;
    font-weight: 500 !important;
    color: #172735 !important;
}
</style>
